package v2

import (
	"fmt"
	"time"

	"github.com/mars/pkg/randid"
)

const (
	timeFormat = "20060102150405"
	// 这个要和数据库保持一致
	defaultDsu = "00001"
)

type IDGetter interface {
	Get() string
}

type defaultIDGetter struct {
	RandId randid.RandIdGetter
	Dsu    string
	AppId  string
	Bucket string
	date   string // 时间格式：20060102150405
	random string // 随机字符串
}

var _ IDGetter = (*defaultIDGetter)(nil)

func (id *defaultIDGetter) Get() string {
	return id.date + "-" + id.Dsu + "-" + id.AppId + "-" + id.Bucket + "-" + id.random
}

type IdGetterBuilder struct {
	idGetter *defaultIDGetter
}

func DefaultIDGetterBuilder() *IdGetterBuilder {
	return &IdGetterBuilder{
		idGetter: &defaultIDGetter{},
	}
}

func (builder *IdGetterBuilder) WithDsu(dsu string) *IdGetterBuilder {
	if len(dsu) == 0 {
		dsu = defaultDsu
	}
	builder.idGetter.Dsu = dsu
	return builder
}

func (builder *IdGetterBuilder) WithAppId(appId string) *IdGetterBuilder {
	builder.idGetter.AppId = appId
	return builder
}

func (builder *IdGetterBuilder) WithBucket(bucket string) *IdGetterBuilder {
	builder.idGetter.Bucket = bucket
	return builder
}

func (builder *IdGetterBuilder) WithRandId(randId randid.RandIdGetter) *IdGetterBuilder {
	builder.idGetter.RandId = randId
	return builder
}

func (builder *IdGetterBuilder) Build() (IDGetter, error) {
	if len(builder.idGetter.Dsu) == 0 || len(builder.idGetter.AppId) == 0 ||
		len(builder.idGetter.Bucket) == 0 {
		return nil, fmt.Errorf("dsu/appId/bucket can't be empty")
	}

	if builder.idGetter.RandId == nil {
		builder.idGetter.RandId = randid.NewDefaultSecureRandom()
	}

	randId, err := builder.idGetter.RandId.Get()
	if err != nil {
		return nil, err
	}

	builder.idGetter.random = randId
	builder.idGetter.date = time.Now().Format(timeFormat)
	return builder.idGetter, nil
}
